package org.ghost.springboot2.demo.util;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;

import java.nio.charset.StandardCharsets;

/**
 * @author 01
 */
public class Base64Util {
    private static final Logger logger = LoggerFactory.getLogger(Base64Util.class);

    private Base64Util() {

    }

    public static String encode(String input) {
        if (StringUtils.isNotBlank(input)) {
            return Base64Utils.encodeToString(input.getBytes(StandardCharsets.UTF_8));
        }
        return input;
    }

    public static String decode(String input) {
        if (StringUtils.isNotBlank(input)) {
            byte[] bytes = Base64Utils.decodeFromString(input);
            if (ArrayUtils.isNotEmpty(bytes)) {
                return new String(bytes, StandardCharsets.UTF_8);
            }
        }
        return input;
    }

    public static String encodeToUrlSafeString(String url) {
        if (StringUtils.isNotBlank(url)) {
            return Base64Utils.encodeToUrlSafeString(url.getBytes(StandardCharsets.UTF_8));
        }
        return url;
    }

    public static String decodeFromUrlSafeString(String url) {
        if (StringUtils.isNotBlank(url)) {
            byte[] bytes = Base64Utils.decodeFromUrlSafeString(url);
            if (ArrayUtils.isNotEmpty(bytes)) {
                return new String(bytes, StandardCharsets.UTF_8);
            }
        }
        return url;
    }


}
